<template>
  <div class="header-search">
    <svg-icon icon="search"
              class="search-icon"
              @click="onShowClick"
              id="guide-search"></svg-icon>
    <el-select v-model="
              searchValue"
              filterable
              placeholder="Select"
              class="header-search-select"
              :class="{show: isShow}"
              remote
              :remote-method="querySearch"
              @blur="loseBlur"
              v-focus>
      <el-option v-for="item in searchOption"
                 :value="item.item"
                 :key="item.item.path"
                 :label="item.item.titles.join(' > ')"
                 @change="changeOption"></el-option>
      </el-select>
  </div>
</template>

<script setup>
const { ref } = require("vue");
import getRoutePool from '@/assets/js/handleData.js'
import Fuse from 'fuse.js'
import { useRouter } from 'vue-router';

const router = useRouter();

const searchValue = ref({});
const isShow = ref(false);
const searchOption = ref([]);

const onShowClick = () => {
  isShow.value = !isShow.value
}

const querySearch = (cin) => {
  searchOption.value = fuse.search(cin)
}

const pool = getRoutePool();

const fuse = new Fuse(pool, {
  shouldSort: true,

  keys: [
    { name: 'title', weight: 0.7 },
    { name: 'path', weight: 0.3 }
  ]
});

const onClose = () => {
  isShow.value = false;
  searchOption.value = [];
  searchValue.value = null;
}

const changeOption = (val) => {
  onClose();
  router.push(val.path);
}

const loseBlur = () => {
  if (isShow.value)
    isShow.value = false;
}

const vFocus = {
  mounted: (el) => el.focus()
}
</script>

<style lang="scss" scoped>
.header-search {
  font-size: 0 !important;
  .search-icon {
    cursor: pointer;
    font-size: 18px;
    vertical-align: middle;
  }

  .header-search-select {
    font-size: 18px;
    transition: width 0.2s;
    width: 0;
    overflow: hidden;
    background: transparent;
    border-radius: 0;
    display: inline-block;
    vertical-align: middle;
    &.show {
      width: 210px;
      margin-left: 10px;
    }

    :deep(.el-input__wrapper) {
      box-shadow: none !important;

      .el-input__inner {
        border-bottom: 1px solid #d9d9d9;
      }
    }
  }
}
</style>